package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.QiniuYunUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    ContractProductService contractProductService;

    @Reference
    FactoryService factoryService;

    @RequestMapping(value = "list",name = "货物列表")
    public String findAll(
            @RequestParam(defaultValue = "1")int page,
            @RequestParam(defaultValue = "10")int size,
            String contractId){
        //1.查询货物列表
        //创建条件对象
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria contractProductExampleCriteria = contractProductExample.createCriteria();
        //设置条件
        contractProductExampleCriteria.andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(page, size, contractProductExample);
        request.setAttribute("page",pageInfo);

        //2.查询生产货物厂家列表
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        factoryExampleCriteria.andCtypeEqualTo("货物");
        //设置排序
        factoryExample.setOrderByClause("factory_name asc");
        List<Factory> list = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",list);

        //3.还需要将合同的id放入域中,方便做货物的添加操作
        request.setAttribute("contractId",contractId);

        return "cargo/product/product-list";
    }

    @RequestMapping(value = "edit",name = "保存或更新货物")
    //MultipartFile 参数名字必须是页面上文件框的name属性值
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) throws IOException {

        if (StringUtils.isBlank(contractProduct.getId())) {
            //文件上传
            if (!productPhoto.isEmpty()) {
                //获取文件的字节数组,调用七牛云工具类完成上传操作
                String url = QiniuYunUtils.upload(productPhoto.getBytes());
                //将返回值设置给货物
                contractProduct.setProductImage(url);
            }

            //保存
            contractProductService.save(contractProduct);
        }else{
            //更新
            contractProductService.update(contractProduct);
        }



        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    @RequestMapping(value = "toUpdate",name = "跳转到货物更新页面")
    public String toUpdate(String id){
        //1.查询该货物的信息
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        //2.查询所有生产货物的厂家信息
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        factoryExampleCriteria.andCtypeEqualTo("货物");
        //设置排序
        factoryExample.setOrderByClause("factory_name asc");
        List<Factory> list = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",list);
        return "cargo/product/product-update";
    }

    @RequestMapping(value = "delete",name = "删除货物")
    public String deleteById(String id,String contractId){
        contractProductService.deleteById(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    @RequestMapping(value = "toImport",name = "跳转到批量上传货物页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }


    @RequestMapping(value = "import",name = "批量上传货物")
    public String batchSave(String contractId,MultipartFile file) throws IOException {
        //1. 创建workbook,加载xlsx文件
        Workbook wk = new XSSFWorkbook(file.getInputStream());
        //2. 获取第一页sheet
        Sheet sheet = wk.getSheetAt(0);
        //3. 创建一个货物的集合,用来存放所有的货物
        List<ContractProduct> list = new ArrayList<>();

        //4. 通过sheet获取所有行,从第二行开始遍历,获取到每行
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            //为了封装数据方便,在实体中提供了一个带参的构造器,只需要将解析的内容放入一个数组中
            Object[] arr = new Object[10];

            //5. 获取到行中每个单元格中内容,一行中的数据封装成一个货物,将每个货物放入list中
            for (int j = 1; j <  row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                arr[j] = getCellValue(cell);
            }

            ContractProduct contractProduct = new ContractProduct(arr,getCompanyId(),getCompanyName());
            //给每个获取设置合同id
            contractProduct.setContractId(contractId);
            list.add(contractProduct);
        }
        //6. 调用contractProductService.batchSave(list),完成保存操作
        contractProductService.batchSave(list);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    //根据每个单元格的数据类型获取数据
    private static Object getCellValue(Cell cell) {
        Object obj = null;

        //获取每个单元格类型,根据类型获取值
        CellType cellType = cell.getCellType();

        switch (cellType) {
            case STRING:
                obj = cell.getStringCellValue();
                break;
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case NUMERIC:
                //判断是否可以解析为日期
                if (DateUtil.isCellDateFormatted(cell)) {
                    obj = cell.getDateCellValue();
                } else {
                    obj = cell.getNumericCellValue();
                }
                break;
            default:
                obj = cell.getStringCellValue();
        }
        return obj;
    }

}
